{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import unicodecsv as csv\n",
    "import json\n",
    "import re\n",
    "import requests\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "24466"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# this gets updated every day \n",
    "data = requests.get(\"http://api.steampowered.com/ISteamApps/GetAppList/v0001/\").json()\n",
    "apps = data['applist']['apps']['app']\n",
    "len(apps)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "24464"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "last_appid_read = 0\n",
    "\n",
    "for app in apps:\n",
    "    appid = app['appid']\n",
    "    \n",
    "    last_appid_read += 1\n",
    "    \n",
    "    if int(appid) == 460010:\n",
    "        break\n",
    "\n",
    "last_appid_read"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{u'appid': 460040, u'name': u'Empires Dedicated Server'}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "apps[24464]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{u'appid': 5, u'name': u'Dedicated Server'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "apps[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def clean_text(input_str):\n",
    "    input1 = re.sub('\\r|\\n|\\r\\n','',input_str)\n",
    "    input2 = re.sub('<[^>]+>','',input1)\n",
    "    input3 = re.sub('\\s+',' ',input2)\n",
    "    input4 = input3.lower()\n",
    "    \n",
    "    # no need for more preprocessing because sklearn's tfidfvectorizer will clean it up prior to\n",
    "    # featurizing\n",
    "    \n",
    "    return input4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "no success for appid 460040, got success=False\n"
     ]
    }
   ],
   "source": [
    "base_url = \"http://store.steampowered.com/api/appdetails?appids=\"\n",
    "\n",
    "apps_remaining = apps[last_appid_read:]\n",
    "\n",
    "with open('../../data/steam/data.csv','a') as csvfile:\n",
    "    fieldnames = ['appid','type','name','detailed_description','about_the_game','categories','genres']\n",
    "    writer = csv.DictWriter(csvfile,fieldnames=fieldnames)\n",
    "    \n",
    "#     writer.writeheader()\n",
    "    \n",
    "    for app in apps_remaining:\n",
    "        appid = app['appid']\n",
    "        address = base_url+str(appid)\n",
    "        \n",
    "        try:\n",
    "            data = requests.get(address).json()  \n",
    "        except requests.ConnectionError:\n",
    "            print(\"failed to retrieve appid {0}, let's wait a minute then try again\".format(appid))\n",
    "            # wait a bit then try again\n",
    "            time.sleep(60)\n",
    "            try:\n",
    "                data = requests.get(address).json()\n",
    "            except requests.ConnectionError:\n",
    "                print(\"failed to retrieve appid {0}, skipping\".format(appid))\n",
    "                # but if if fails again give up\n",
    "                continue\n",
    "        \n",
    "        success = data[str(appid)]['success']\n",
    "              \n",
    "        if not (success == \"True\" or success == True):\n",
    "            \n",
    "            print(\"no success for appid {0}, got success={1}\".format(appid,success))\n",
    "            time.sleep(2)\n",
    "            continue\n",
    "        \n",
    "        \n",
    "        app_data = data[str(appid)]['data']\n",
    "        \n",
    "        data_dict = dict()\n",
    "        data_dict['appid'] = appid      \n",
    "        data_dict['name'] = app_data['name']\n",
    "        data_dict['type'] = app_data['type']\n",
    "        \n",
    "        try:\n",
    "            data_dict['detailed_description'] = clean_text(app_data['detailed_description'])          \n",
    "        except KeyError:\n",
    "            data_dict['detailed_description'] = ''\n",
    "        \n",
    "        try:\n",
    "            data_dict['about_the_game'] =  clean_text(app_data['about_the_game'])           \n",
    "        except KeyError:\n",
    "            data_dict['about_the_game'] = ''\n",
    "               \n",
    "        try:\n",
    "            data_dict['categories'] =   \",\".join(map(lambda d: d['description'],app_data['categories']))\n",
    "        except KeyError:\n",
    "            data_dict['categories'] = 'Uncategorized'\n",
    "        \n",
    "        try:\n",
    "            data_dict['genres'] = \",\".join(map(lambda d: d['description'],app_data['genres']))\n",
    "        except KeyError:\n",
    "            data_dict['genres'] = 'Uncategorized'\n",
    "                       \n",
    "        writer.writerow(data_dict)          \n",
    "\n",
    "        time.sleep(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
